import React,{ Component } from 'react';
import {NavLink} from 'react-router-dom';
import {Footer} from '../Components';
import {connect} from 'react-redux';
import {createStore} from 'redux';
import mapStateToProps from '../value/mapStateToProps';
import {addToCart,addToCard} from '../action/counter';
function objchangestring(obj){
	var arr=[];
	for(var i in obj){
		arr.push(i+'='+obj[i]);
	}
	return arr.join('&');
}
// var $ = (function(){
//     var ajax=function(url,callback,obj){
//          var xhr=new XMLHttpRequest();
//          xhr.open("POST",url,true);
//          if(obj){
//             var Obj=objchangestring(obj);
//             xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
//          xhr.send(Obj); 
//          }else{
//             xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
//             xhr.send('');   
//          }
//          xhr.onreadystatechange=function(){
//            if(xhr.readyState==4&&xhr.status==200){
//                  callback(JSON.parse(xhr.responseText));
//            }
//          }
//     }
//     return {
//       http:ajax    
//      }

//  })();

 class Product extends Component{
    constructor(props) {
        super(props);


        this.props={
            src:{
                url:'http://10.31.160.25:3000/product/list'
            }
           
        }

        
    this.state={
        page:{
            num:1,
        },
        data:{
            data:[1]
        }
   }
    }
    handl(e){
        var that=this;
        var ele=document.getElementsByClassName('pagination')[0].childNodes;
        var length=ele.length;
        for(var i=0;i<length;i++){
            ele[i].className=''
        };
        e.target.parentNode.className='active';
       that.setState({ 
        page:Object.assign({},that.state.page,{num:e.target.getAttribute('value')})
       });
       this.getdata({page:e.target.getAttribute('value')})
    }
    hotClick(data){
        if(isNaN(data.hotclick)){
           data.hotclick=0;
         
        }
         var hotclick= data.hotclick
             ++hotclick
              $.ajax({
                 type: 'put',
                 url: `http://10.31.160.25:3000/product/data/${data._id}`,
                 data:{
                      hotclick:hotclick
                 }
             })
     }
     addCart(e){
           var idx=e.target.getAttribute('data-id');
           this.props.addToCart({id:idx});
           if(confirm('添加成功，去付款吗？')){
            this.props.history.push('/cart') ; //路由跳转，去购物车                         
           }else{
            this.props.history.push('/product') ; //路由跳转，回到产品页       
           }

     }
    getdata(a){
        var arr=[];
        var that=this;
        $.ajax({
            type: 'post',
            url:'http://10.31.160.25:3000/product/list',
            data:{...a}
        }).then(data=>{
            arr.push(data.rows)
            that.setState({
                data: Object.assign({}, that.state.data, {data:arr}),
            })   
    });
    }
    componentWillMount(){
        console.log('mount');
        this.getdata({page:1});
    }
    shouldComponentUpdate(nextProps,nextState){
        console.log("shouldComponentUpdate");
            return true;    
    }
    componentWillUpdate(){
        console.log('update')
        //this.getdata({page:this.state.page.num})
    }
    componentDidUpdate(){
        console.log('success')
    }
    render(){
        //console.log(this.props)
        var style= { width:"84%",height:"200px",marginTop:'20px'};
        var style1={height:'100px',textAlign:'center'};
        let list = [];
           console.log(this.state.data.data[0]);
			for(var i=0;i<this.state.data.data[0].length;i++){
                var a=this.state.data.data[0][i];
                
                var link='/detail/'+a._id+"/"+this.state.page.num+"/"+a.title;
              // console.log(this.state.data.data[0][0]);
              //  console.log(link);
                list.push(
                    <div className="col-sm-6 col-md-3">
                    <div className="thumbnail">
                <img src={this.state.data.data[0][i].src} alt={this.state.data.data[0][i].title} style={style}/>
                <div className="caption">
                    <h3  style={style1}>{this.state.data.data[0][i].title}</h3>
                    <p>{this.state.data.data[0][i].desc}</p>
                    <p style={{color:'red',position:'relative'}}>价格：￥{this.state.data.data[0][i].price}<span style={{color:'grey',display:'inline-block',position:'absolute',right:'8px'}}>点击量：{this.state.data.data[0][i].hotclick}</span></p>
                    <p><NavLink to={link}><a href="#" className="btn btn-primary" role="button" onClick={this.hotClick.bind(this,this.state.data.data[0][i])}>查看详情 </a></NavLink><a href="javascript:;" className="btn btn-default" data-id={this.state.data.data[0][i]._id} onClick={this.addCart.bind(this)} role="button">加入购物车</a></p>
                </div>
                </div>
                
                    </div>
                )
            }
        return(
            <div>
                 <div className="row">
                    {list}
                        
                    </div>
            
                <nav aria-label="..." className="text-center" onClick={this.handl.bind(this)}>
                    <ul className="pagination" >
                        <li className="disabled">
                            <span>
                            <span aria-hidden="true">&laquo;</span>
                            </span>
                        </li>
                        <li>
                        <span  value='1'>1 <span className="sr-only">(current)</span></span>
                        </li>
                        <li>
                        <span value='2'>2<span className="sr-only">(current)</span></span>
                        </li><li>
                        <span value='3'>3 <span className="sr-only">(current)</span></span>
                        </li><li>
                        <span value='4'>4 <span className="sr-only">(current)</span></span>
                        </li><li>
                        <span value='5'>5 <span className="sr-only">(current)</span></span>
                        </li><li>
                        <span value='6'>6 <span className="sr-only">(current)</span></span>
                        </li>
                        <li className="disabled">
                            <span>
                            <span aria-hidden="true">&raquo;</span>
                            </span>
                        </li>
                    </ul>
                </nav>
                <Footer/>
            </div>
        )
    }
}
export default connect(mapStateToProps,{addToCart,addToCard})(Product)